package cn.jhoncy.jproject.framework.security.Authentication;

import cn.jhoncy.jproject.framework.security.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.*;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 鉴权：自定义认证
 * Created by zhuangqi on 17-4-17.
 */
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Bean
    public Md5PasswordEncoder md5PasswordEncoder() {
        return new Md5PasswordEncoder();
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String username = token.getName();
        //从数据库找到的用户
        UserDetails userDetails = null;
        if (username != null) {
            userDetails = customUserDetailsService.loadUserByUsername(username);
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException("用户已被禁用");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("账号已过期");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("账号已被锁定");
        } else if (!userDetails.isCredentialsNonExpired()) {
            throw new LockedException("凭证已过期");
        }
        //数据库用户的密码
        String encPass = userDetails.getPassword();

        //与authentication里面的credentials相比较
        Md5PasswordEncoder md5PasswordEncoder = this.md5PasswordEncoder();
        if (!md5PasswordEncoder.isPasswordValid(encPass, token.getCredentials().toString(), null)) {
            throw new BadCredentialsException("Invalid username/password");
        }
        //将用户信息存入Authentication的Token中，将由spring-Security自动鉴权。
        return new UsernamePasswordAuthenticationToken(userDetails, encPass, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //token中的name是否与security保存的用户信息中的name是否相同，如果相同鉴权成功
        return UsernamePasswordAuthenticationToken.class.getName().equals(authentication.getName());
    }
}
